/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.source.web.program;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thinkgem.jeesite.common.utils.I18nUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContextUtils;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.equipment.entity.EleEquipment;
import com.thinkgem.jeesite.modules.equipment.service.EleEquipmentService;
import com.thinkgem.jeesite.modules.source.entity.EleSource;
import com.thinkgem.jeesite.modules.source.entity.EleSourceGroup;
import com.thinkgem.jeesite.modules.source.entity.program.EleSourceProgram;
import com.thinkgem.jeesite.modules.source.service.EleSourceGroupService;
import com.thinkgem.jeesite.modules.source.service.program.EleSourceProgramService;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import com.thinkgem.jeesite.modules.templet.service.EleTempletService;

/**
 * 固件程序管理Controller
 * @author unnamed
 * @version 2017-12-20
 */
@Controller
@RequestMapping(value = "${adminPath}/source/program/eleSourceProgram")
public class EleSourceProgramController extends BaseController {

	@Autowired
	private EleSourceProgramService eleSourceProgramService;
	@Autowired
	private EleSourceGroupService eleSourceGroupService;	
	@Autowired
	private OfficeService officeService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private EleEquipmentService eleEquipmentService;
	@Autowired
	private EleTempletService eleTempletService;	
	
	
	@ModelAttribute
	public EleSourceProgram get(@RequestParam(required=false) String id) {
		EleSourceProgram entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = eleSourceProgramService.get(id);
		}
		if (entity == null){
			entity = new EleSourceProgram();
		}
		return entity;
	}
	
	@RequiresPermissions("source:program:eleSourceProgram:view")
	@RequestMapping(value = {"list", ""})
	public String list(EleSourceProgram eleSourceProgram, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<EleSourceProgram> page = eleSourceProgramService.findPage(new Page<EleSourceProgram>(request, response), eleSourceProgram); 
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		page.setLocale(locale);
		model.addAttribute("page", page);
		model.addAttribute("language", locale.getLanguage());
		if(locale.getLanguage().equals(Locale.CHINESE.getLanguage())){
			model.addAttribute("langCode", locale.getLanguage()+"-cn");
		}else{
			model.addAttribute("langCode", locale.getLanguage());
		}
		return "modules/source/program/eleSourceProgramList";
	}

	@RequiresPermissions("source:program:eleSourceProgram:view")
	@RequestMapping(value = "form")
	public String form(EleSourceProgram eleSourceProgram,HttpServletRequest request, Model model) {
		if("mcu".equals(eleSourceProgram.getType())) {
			eleSourceProgram.setPath2(eleSourceProgram.getPath());
		} else {
			eleSourceProgram.setPath1(eleSourceProgram.getPath());
		}
		model.addAttribute("eleSourceProgram", eleSourceProgram);
		Locale locale = RequestContextUtils.getLocaleResolver(request).resolveLocale(request);  
		model.addAttribute("language", locale.getLanguage());
		if(locale.getLanguage().equals(Locale.CHINESE.getLanguage())){
			model.addAttribute("langCode", locale.getLanguage()+"-cn");
		}else{
			model.addAttribute("langCode", locale.getLanguage());
		}
		return "modules/source/program/eleSourceProgramForm";
	}

	@RequiresPermissions("source:program:eleSourceProgram:edit")
	@RequestMapping(value = "save")
	public String save(EleSourceProgram eleSourceProgram,HttpServletRequest request, Model model, RedirectAttributes redirectAttributes) {

		if("mcu".equals(eleSourceProgram.getType())) {
			eleSourceProgram.setPath(eleSourceProgram.getPath2());
		} else {
			eleSourceProgram.setPath(eleSourceProgram.getPath1());
		}

		if (!beanValidator(model, eleSourceProgram)){
			return form(eleSourceProgram,request, model);
		}

		eleSourceProgramService.save(eleSourceProgram);
		
		if(!StringUtils.isEmpty(eleSourceProgram.getGroupId())) {
			eleSourceGroupService.deleteFromDB(eleSourceProgram.getGroupId());
		}
		
		EleSourceGroup eleSourceGroup = new EleSourceGroup();
		eleSourceGroup.setName(eleSourceProgram.getType()+"-"+eleSourceProgram.getVersion());
		eleSourceGroup.setVisible("0");
		eleSourceGroup.setType("program");
		eleSourceGroup.setDelFlag(EleSourceGroup.DEL_FLAG_NORMAL);
		EleSource source = new EleSource();
		source.setId("");
		source.setType(eleSourceProgram.getType());
		source.setName(eleSourceProgram.getType()+"Generated");
		source.setContent(eleSourceProgram.getId());
		
		List<EleSource> esList = Lists.newArrayList();
		esList.add(source);
		eleSourceGroup.setEleSourceList(esList);

		
		eleSourceGroupService.save(eleSourceGroup);
		String basePath = Global.getUserfilesBaseDir();

		eleTempletService.createPackageForProgramSourceGroup(eleSourceGroup, basePath);
		
		eleSourceProgramService.updateGroupId(eleSourceGroup.getId(), eleSourceProgram.getId());
		String locale = I18nUtils.getLocaleStr();
		String msg = "保存固件程序管理成功";
		if(Global.US.equals(locale)){
			msg = "Save firmware program management success";
		}
		addMessage(redirectAttributes, msg);
		return "redirect:"+Global.getAdminPath()+"/source/program/eleSourceProgram/?repage";
	}
	
	@RequiresPermissions("source:program:eleSourceProgram:edit")
	@RequestMapping(value = "applypublish")
	public String applypublish(EleSourceProgram eleSourceProgram, Model model, RedirectAttributes redirectAttributes) {
		// Edited by jyz (2018.5)
		String basePath = Global.getUserfilesBaseDir();
		String zipPath = basePath + "/theme/source/"+eleSourceProgram.getGroupId()+"/" + eleSourceProgram.getGroupId() + ".zip";
		File zipFile = new File(zipPath);
		if(!zipFile.exists()) {
			String locale = I18nUtils.getLocaleStr();
			String msg = "该固件文件不存在，请重新上传";
			if(Global.US.equals(locale)){
				msg = "The firmware file does not exist, please re-upload";
			}
			addMessage(redirectAttributes, msg);
			return "redirect:"+Global.getAdminPath()+"/source/program/eleSourceProgram/?repage";
		}

		EleSourceGroup eleSourceGroup = eleSourceGroupService.getGroupById(eleSourceProgram.getGroupId());
		EleEquipment eleEquipment = new EleEquipment();
		List<Office> listTree = new ArrayList<>();

        User current = UserUtils.getUser();
       
		List<User> resultList = systemService.getBranchForUserWithSelf(current);
		Set<String> ids = new HashSet<String>();
		for(User temuser:resultList){
			System.out.println(temuser.getLoginName());
			 String officeId = temuser.getOffice().getId();
			 String companyId = temuser.getCompany().getId();
			ids.add(officeId);
			ids.add(companyId);
		}
		List<Office> listOffice = officeService.findList(true);
		
	
		Set<String> officeIds = new HashSet<>();
		Set<String> eqIds = new HashSet<>();
		for(User tmp:resultList){
			EleEquipment eleEquipmentTmp = new EleEquipment();
			eleEquipmentTmp.setCompany(tmp.getCompany());
			eleEquipmentTmp.setOffice(tmp.getOffice());

			List<EleEquipment> listEquipment = eleEquipmentService.findList(eleEquipmentTmp);
			for (EleEquipment equipment : listEquipment) {
				officeIds.add(equipment.getCompany().getId());
				officeIds.add(equipment.getOffice().getId());
				if(eqIds.contains(equipment.getId())){
					continue;
				}
				eqIds.add(equipment.getId());
				Office Office = new Office();
				Office.setId(equipment.getId());
				Office.setParent(new Office(equipment.getOffice().getId()));
				Office.setAddress(equipment.getCode());
				Office.setEmail(equipment.getType().getName());
				Office.setFax(equipment.getWidth() + " X " + equipment.getHeight());
				Office.setRemarks(equipment.getRemarks());
				if("1".equals(equipment.getState())){
					Office.setGrade("在线");
				}else{
					Office.setGrade("离线");
				}
				Office.setPhone("");
				Office.setZipCode(equipment.getName());

				listTree.add(Office);

			}
		}
		System.out.println(listTree.size()+"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB");

		Set<String> resultSet = new HashSet<String>();
		for (String oid : officeIds) {
			resultSet.add(oid);
			Office tmp = officeService.get(oid);
			for (int i = 0; i < listOffice.size(); i++) {
				Office item = listOffice.get(i);
				if (item.getId().equals(tmp.getParentId())) {
					System.out.println(item);
					tmp = item;
					i = -1;
					resultSet.add(item.getId());
				}
			}
		}
		for(String oid:resultSet){
			Office item = officeService.get(oid);
			item.setAddress(null);
			item.setEmail(null);
			item.setFax(null);
			item.setRemarks(null);
			item.setGrade(null);
			item.setPhone("display:none;");
			item.setZipCode("");

			listTree.add(item);
		}
			model.addAttribute("list", listTree);
			model.addAttribute("user", current);
			model.addAttribute("eleEquipment", eleEquipment);
			model.addAttribute("eleSourceGroup", eleSourceGroup);
			model.addAttribute("resourcetype", "program");

			return "modules/source/eleSourceGroupPublish";
	}
	
	
	@RequiresPermissions("source:program:eleSourceProgram:edit")
	@RequestMapping(value = "delete")
	public String delete(EleSourceProgram eleSourceProgram, RedirectAttributes redirectAttributes) {
		eleSourceProgramService.delete(eleSourceProgram);
		String locale = I18nUtils.getLocaleStr();
		String msg = "删除固件程序管理成功";
		if(Global.US.equals(locale)){
			msg = "Delete firmware program management success";
		}
		addMessage(redirectAttributes, msg);
		return "redirect:"+Global.getAdminPath()+"/source/program/eleSourceProgram/?repage";
	}

}